package com.excilys.gwtfirst.domain.dao.impl;

import java.util.List;

import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import com.excilys.gwtfirst.domain.dao.api.IUserDAO;
import com.excilys.gwtfirst.domain.dao.exception.UserAlreadyExistsException;
import com.excilys.gwtfirst.domain.model.User;

@Repository
@SuppressWarnings("unchecked")
public class UserDAO extends HibernateDaoSupport implements IUserDAO {

	@Override
	public User findById(Integer id) {
		List<User> users = getHibernateTemplate().find("from User where id = ?", id);
		return users.isEmpty() ? null : users.get(0);
	}

	public User findByLogin(String login) {
		List<User> users = getHibernateTemplate().find("from User where login = ?", login);
		return users.isEmpty() ? null : users.get(0);
	}

	@Override
	public List<User> findAll() {
		return getHibernateTemplate().find("from User");
	}

	@Override
	public void save(User user) throws UserAlreadyExistsException {
		try {
			getHibernateTemplate().save(user);
		} catch (DataIntegrityViolationException e) {
			throw new UserAlreadyExistsException(user.getLogin());
		}
	}

}
